package com.pmcc.core.service;

import com.pmcc.core.entity.security.Attachment;
import com.pmcc.core.repository.SystemAttachmentRepository;
import com.pmcc.core.vo.ImageVo;
import com.pmcc.utils.CommonVariables;
import com.pmcc.utils.DateUtil;
import com.pmcc.utils.ResultBean;
import com.pmcc.utils.UUIDGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by zzy on 2018/3/19.
 * 附件上传下载 service 层
 */

@Service
@Transactional
public class SystemAttachmentService {

    @Autowired
    SystemAttachmentRepository attachmentRepository;

    @Value("${upload.path}")
    private String path;//真实路径

    @Value("${upload.readPath}")
    private String readPath;//虚拟路径

    public ResultBean updateAttachmentById(String businessDateId, String id) {
        ResultBean resultBean = new ResultBean();
        Integer updateDate = attachmentRepository.updateAttachmentById(businessDateId, id);
        if (updateDate != null) {
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setResultDesc("更新成功");
        } else {
            resultBean.setResultCode(ResultBean.FAIL);
            resultBean.setResultDesc("更新失败");
        }
        return resultBean;
    }


    /**
     * 通过IDS 更新
     *
     * @param businessDateId
     * @param idsList
     * @return
     */
    public ResultBean updateAttachmentByIds(String businessDateId, List<String> idsList) {
        ResultBean resultBean = new ResultBean();
        Integer updateDates = attachmentRepository.updateAttachmentByIds(businessDateId, idsList);
        if (updateDates != null) {
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setResultDesc("更新成功");
        } else {
            resultBean.setResultCode(ResultBean.FAIL);
            resultBean.setResultDesc("更新失败");
        }
        return resultBean;
    }

    /**
     * 通过businessDateId 附件信息
     *
     * @param businessDateId
     * @return
     */
    public ResultBean queryAttachment(String businessDateId) {
        ResultBean resultBean = new ResultBean();
        List<Attachment> attachmentList = attachmentRepository.findByBusinessDataIdAndDelFlag(businessDateId, "0");
        if (attachmentList != null) {
            if (attachmentList.size() > 0) {
                List<ImageVo> imageVoList = new ArrayList<>();
                for (Attachment model : attachmentList) {
                    ImageVo imageVo = new ImageVo();
                    imageVo.setUid(model.getId());
                    imageVo.setName(model.getFileName());
                    imageVo.setStatus("done");
                    imageVo.setUrl(model.getFileUrl());
                    imageVoList.add(imageVo);
                }
                resultBean.setRows(imageVoList);
                resultBean.setResultCode(ResultBean.SUCCESS);
                resultBean.setResultDesc("获取成功");
            } else {
                resultBean.setRows(attachmentList);
                resultBean.setResultCode(ResultBean.SUCCESS);
                resultBean.setResultDesc("暂无数据");
            }
        } else {
            resultBean.setResultCode(ResultBean.FAIL);
            resultBean.setResultDesc("附件获取失败,请稍后重试");
        }
        return resultBean;
    }

    /**
     * 单文件上传 不保存附件表的方法
     *
     * @param file          文件
     * @param serviceFolder 文件夹的名称
     * @return
     */
    public ResultBean uploadFile(MultipartFile file, String serviceFolder) {
        ResultBean resultBean = new ResultBean();
        resultBean.setResultCode(ResultBean.SUCCESS);
        resultBean.setResultDesc("上传成功！");
        // 原文件名称
        String originalFilename = file.getOriginalFilename();
        String[] arr = originalFilename.split("\\.");
        // 文件类型
        String fileType = arr.length > 1 ? arr[arr.length - 1] : "";

        String imgType = "webp,svg,png,gif,jpg,jpeg,bmp,WEBP,SVG,PNG,GIF,JPG,JPEG,BMP";
        if (StringUtils.isNotEmpty(fileType) && imgType.contains(fileType)) {
            fileType = fileType.toLowerCase();
        }
        // 存放在服务器端的文件名
        String serverFileName = StringUtils.isEmpty(fileType) ? UUIDGenerator.getUUID() : UUIDGenerator.getUUID() + "." + fileType;//附件上传上去后的随机名称
        // 创建文件夹  年-月-日
        String folder = DateUtil.DateToString(new Timestamp(new Date().getTime()), "yyyy-MM-dd");
        // 数据库存放路径：文件名/年-月-日
        String filePath = serviceFolder + "/" + folder + "/";

        // 服务器存放附件文件夹
        File targetFile = new File(path, filePath);
        boolean flag = true;
        if (!targetFile.exists()) {
            flag = targetFile.mkdirs();
        }
        if (flag) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(path + filePath + serverFileName)));
                stream.write(bytes);
                stream.close();
                resultBean.setResultData(readPath + filePath + serverFileName);
            } catch (Exception e) {
                resultBean.setResultCode(ResultBean.FAIL);
                resultBean.setResultDesc("上传失败！");
                e.printStackTrace();
            }
        } else {
            resultBean.setResultCode(ResultBean.FAIL);
            resultBean.setResultDesc("上传失败！");
        }
        return resultBean;
    }

    /**
     * 单文件上传 并保存附件表的方法
     *
     * @param file          文件
     * @param serviceFolder 文件夹的名称
     * @return
     */
    public ResultBean uploadFileAndSave(MultipartFile file, String serviceFolder) {
        ResultBean resultBean = new ResultBean();
        resultBean.setResultCode(ResultBean.SUCCESS);
        resultBean.setResultDesc("上传成功！");

        // 原文件名称
        String originalFilename = new String(file.getOriginalFilename());
        String[] arr = originalFilename.split("\\.");
        // 文件类型
        String fileType = arr.length > 1 ? arr[arr.length - 1] : "";
        String imgType = "webp,svg,png,gif,jpg,jpeg,bmp,WEBP,SVG,PNG,GIF,JPG,JPEG,BMP";
        if (StringUtils.isNotEmpty(fileType) && imgType.contains(fileType)) {
            fileType = fileType.toLowerCase();
        }
        // 存放在服务器端的文件名
        String serverFileName = StringUtils.isEmpty(fileType) ? UUIDGenerator.getUUID() : UUIDGenerator.getUUID() + "." + fileType;
        // 创建文件夹  年-月-日
        String folder = DateUtil.DateToString(new Timestamp(new Date().getTime()), "yyyy-MM-dd");
        // 数据库存放路径：年-月-日/文件名
        String filePath = serviceFolder + "/" + folder;

        BufferedOutputStream stream = null;
        File targetFile = new File(path, filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        // 上传文件
        try {
            byte[] bytes = file.getBytes();
            stream = new BufferedOutputStream(new FileOutputStream(new File(path + filePath + "/" + serverFileName)));
            stream.write(bytes);
            stream.close();

            // 附件实体
            Attachment att = new Attachment();

            att.setBusinessModel(serviceFolder);
            att.setFileName(originalFilename);//附件名称
            att.setFileUrl(readPath + filePath + "/" + serverFileName);//附件地址
            att.setFileAliasName(serverFileName);//附件转换名称
            att.setFileType(fileType);//附件类型
            att.setFileSize(file.getSize());//附件大小(单位B)
            att.setDownloadCount(0);//下载次数
            att.setCreateTime(new Date());
            att.setDelFlag(CommonVariables.NO_FLAG);
            attachmentRepository.save(att);
            // 附件主键
            resultBean.setResultData(att.getId());
            resultBean.setObject(att);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
            resultBean.setResultDesc("上传失败！");
            e.printStackTrace();
        }
        return resultBean;
    }


    /**
     * 多文件附件上传到付件表中，返回附件的ID集合
     *
     * @param request
     * @param fileName
     * @param folder
     * @return
     */
    public ResultBean uploads(String businessDataId, HttpServletRequest request, String fileName, String folder) {
        ResultBean resultBean = new ResultBean();
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles(fileName);
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        List<String> imgList = new ArrayList<>();
        for (int i = 0; i < files.size(); i++) {
            file = files.get(i);
            if (!file.isEmpty()) {
                //原始名称
                String originalFilename = file.getOriginalFilename();
                String[] arr = originalFilename.split("\\.");
                // 文件类型
                String fileType = arr.length > 1 ? arr[arr.length - 1] : "";
                String imgType = "webp,svg,png,gif,jpg,jpeg,bmp,WEBP,SVG,PNG,GIF,JPG,JPEG,BMP";
                if (StringUtils.isNotEmpty(fileType) && imgType.contains(fileType)) {
                    fileType = fileType.toLowerCase();
                }
                // 存放在服务器端的文件名
                String fileAliasName = UUIDGenerator.getUUID();
                String serverFileName = StringUtils.isEmpty(fileType) ? fileAliasName : fileAliasName + "." + fileType;
                // 创建文件夹  年-月-日
                String dateTime = DateUtil.DateToString(new Timestamp(new Date().getTime()), "yyyy-MM-dd");
                // 数据库存放路径：年-月-日/文件名
                String filePath = "/" + folder + "/" + dateTime;

                File targetFile = new File(path, filePath);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(new File(path + filePath + "/" + serverFileName)));
                    stream.write(bytes);
                    stream.close();
                } catch (IOException e) {
                    resultBean.setResultCode(ResultBean.FAIL);
                    resultBean.setResultDesc("上传失败！");
                    e.printStackTrace();
                }
                //附件路径
                String imgPath = readPath + filePath + "/" + serverFileName;

                //保存到付件表
                Attachment attachment = new Attachment();
                attachment.setBusinessDataId(businessDataId);
                attachment.setBusinessModel(folder);
                attachment.setFileName(originalFilename);//附件名称
                attachment.setFileUrl(imgPath);//附件地址
                attachment.setFileAliasName(fileAliasName);//附件转换名称
                attachment.setFileType(fileType);//附件类型
                attachment.setFileSize(file.getSize());//附件大小(单位B)
                attachment.setDownloadCount(0);//下载次数
                attachment.setCreateTime(new Date());
                attachment.setDelFlag(CommonVariables.NO_FLAG);
                attachmentRepository.save(attachment);
                imgList.add(attachment.getId());
            }
        }
        resultBean.setResultCode(ResultBean.SUCCESS);
        resultBean.setRows(imgList);
        resultBean.setResultDesc("上传成功！");
        return resultBean;
    }

    /**
     * 根据ID删除
     *
     * @param id   附件id
     * @param type 删除类型 逻辑删除 0 物理删除 1
     * @return
     */
    public void delete(String id, String type) {
        if (type.equals("0")) {
            attachmentRepository.deleteByIds("1", Arrays.asList(id.split(",")));
        } else {
            attachmentRepository.delete(id);
        }
    }


    public ResultBean uploadPersonalLog(String businessDataId, HttpServletRequest request, String fileName, String folder) {
//    @Transactional(propagation = Propagation.REQUIRES_NEW)
//    public ResultBean uploads(HttpServletRequest request, String fileName, String folder) {

        ResultBean resultBean = new ResultBean();
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles(fileName);
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        List<String> imgList = new ArrayList<>();
        for (int i = 0; i < files.size(); i++) {
            file = files.get(i);
            if (!file.isEmpty()) {
                //原始名称
                String originalFilename = file.getOriginalFilename();
                String[] arr = originalFilename.split("\\.");
                // 文件类型
                String fileType = arr.length > 1 ? arr[arr.length - 1] : "";
                String imgType = "webp,svg,png,gif,jpg,jpeg,bmp,WEBP,SVG,PNG,GIF,JPG,JPEG,BMP";
                if (StringUtils.isNotEmpty(fileType) && imgType.contains(fileType)) {
                    fileType = fileType.toLowerCase();
                }
                // 存放在服务器端的文件名
                String fileAliasName = UUIDGenerator.getUUID();
                String serverFileName = StringUtils.isEmpty(fileType) ? fileAliasName : fileAliasName + "." + fileType;
                // 创建文件夹  年-月-日
                String dateTime = DateUtil.DateToString(new Timestamp(new Date().getTime()), "yyyy-MM-dd");
                // 数据库存放路径：年-月-日/文件名
                String filePath = "/" + folder + "/" + dateTime;

                File targetFile = new File(path, filePath);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(new File(path + filePath + "/" + serverFileName)));
                    stream.write(bytes);
                    stream.close();
                } catch (IOException e) {
                    resultBean.setResultCode(ResultBean.FAIL);
                    resultBean.setResultDesc("上传失败！");
                    e.printStackTrace();
                }
                //附件路径
                String imgPath = readPath + filePath + "/" + serverFileName;

                //保存到付件表
                Attachment attachment = new Attachment();
                attachment.setBusinessDataId(businessDataId);
                attachment.setBusinessModel(folder);
                attachment.setFileName(originalFilename);//附件名称
                attachment.setFileUrl(imgPath);//附件地址
                attachment.setFileAliasName(fileAliasName);//附件转换名称
                attachment.setFileType(fileType);//附件类型
                attachment.setFileSize(file.getSize());//附件大小(单位B)
                attachment.setDownloadCount(0);//下载次数
                attachment.setCreateTime(new Date());
                attachment.setDelFlag(CommonVariables.NO_FLAG);
                if (i == 0) {
                    attachment.setRemark("0");
                } else {
                    attachment.setRemark("1");
                }
                attachmentRepository.save(attachment);
                imgList.add(attachment.getId());
            }
        }
        resultBean.setResultCode(ResultBean.SUCCESS);
        resultBean.setRows(imgList);
        resultBean.setResultDesc("上传成功！");
        return resultBean;
    }
}
